import axios from 'axios';
import { Platform } from 'react-native';

// API Configuration
const API_BASE_URL = __DEV__ 
  ? 'http://localhost:8000/api/v1'
  : 'https://your-production-api.com/api/v1';

// Create axios instance
const api = axios.create({
  baseURL: API_BASE_URL,
  timeout: 30000, // 30 seconds
  headers: {
    'Content-Type': 'application/json',
  },
});

// Request interceptor
api.interceptors.request.use(
  (config) => {
    // Add any auth tokens here
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// Response interceptor
api.interceptors.response.use(
  (response) => {
    return response;
  },
  (error) => {
    if (error.response?.status === 429) {
      throw new Error('Too many requests. Please try again later.');
    }
    if (error.response?.status >= 500) {
      throw new Error('Server error. Please try again later.');
    }
    return Promise.reject(error);
  }
);

// API Types
export interface ColorizeParams {
  style?: 'anime' | 'realistic' | 'cartoon' | 'sketch' | 'watercolor';
  strength?: number;
  guidance_scale?: number;
  num_inference_steps?: number;
  seed?: number;
}

export interface ColorizeResponse {
  success: boolean;
  task_id: string;
  status: 'pending' | 'processing' | 'completed' | 'failed';
  original_image_url?: string;
  colored_image_url?: string;
  error_message?: string;
  processing_time?: number;
  metadata?: any;
  created_at: string;
}

export interface TaskStatusResponse {
  task_id: string;
  status: 'pending' | 'processing' | 'completed' | 'failed';
  progress: number;
  result?: ColorizeResponse;
  estimated_time_remaining?: number;
}

// API Service
export class ColorizeService {
  /**
   * Upload and colorize an image
   */
  static async colorizeImage(
    imageUri: string,
    params: ColorizeParams = {}
  ): Promise<ColorizeResponse> {
    const formData = new FormData();
    
    // Convert file URI to blob
    const response = await fetch(imageUri);
    const blob = await response.blob();
    
    formData.append('file', blob);
    
    // Add optional parameters
    Object.entries(params).forEach(([key, value]) => {
      if (value !== undefined) {
        formData.append(key, value.toString());
      }
    });

    const { data } = await api.post('/colorize', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    });

    return data;
  }

  /**
   * Get task status
   */
  static async getTaskStatus(taskId: string): Promise<TaskStatusResponse> {
    const { data } = await api.get(`/colorize/status/${taskId}`);
    return data;
  }

  /**
   * Get task result
   */
  static async getTaskResult(taskId: string): Promise<ColorizeResponse> {
    const { data } = await api.get(`/colorize/result/${taskId}`);
    return data;
  }

  /**
   * Poll task until completion
   */
  static async pollTaskUntilComplete(
    taskId: string,
    onProgress?: (status: TaskStatusResponse) => void,
    maxAttempts: number = 60,
    intervalMs: number = 2000
  ): Promise<ColorizeResponse> {
    let attempts = 0;

    while (attempts < maxAttempts) {
      const status = await this.getTaskStatus(taskId);
      
      if (onProgress) {
        onProgress(status);
      }

      if (status.status === 'completed') {
        if (status.result) {
          return status.result;
        }
        // Fallback to getTaskResult
        return await this.getTaskResult(taskId);
      }

      if (status.status === 'failed') {
        throw new Error(status.result?.error_message || 'Processing failed');
      }

      await new Promise(resolve => setTimeout(resolve, intervalMs));
      attempts++;
    }

    throw new Error('Processing timeout');
  }

  /**
   * Health check
   */
  static async healthCheck(): Promise<any> {
    const { data } = await api.get('/health');
    return data;
  }
}

// Export configured API instance
export default api;
